import { FastifyRequest } from 'fastify';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { CallHandler, ExecutionContext, Injectable, Logger, NestInterceptor } from '@nestjs/common';

@Injectable()
export class LoggerInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        const start = Date.now();
        const request = context.switchToHttp().getRequest() as FastifyRequest;
        const reqHeaders: any = request.headers;
        const urlInfo = `${request.method} ${request.url}`;

        return next
            .handle()
            .pipe(
                tap(() =>
                    Logger.log(`请求接口: ${urlInfo}, 响应时间: ${Date.now() - start} ms  请求来源: ${reqHeaders.host}`)
                )
            );
    }
}
